package com.teaxiaoyi.tea_xiaoyi.services.impl;

import com.teaxiaoyi.tea_xiaoyi.common.AppResult;
import com.teaxiaoyi.tea_xiaoyi.common.ResultCode;
import com.teaxiaoyi.tea_xiaoyi.dao.employeeMapper;
import com.teaxiaoyi.tea_xiaoyi.exception.ApplicationException;
import com.teaxiaoyi.tea_xiaoyi.model.employee;
import com.teaxiaoyi.tea_xiaoyi.services.IEmployeeService;
import com.teaxiaoyi.tea_xiaoyi.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class EmployeeServiceimpl implements IEmployeeService {


    @Resource
    private employeeMapper employeeMapper;

    @Override
    public void createEmployee(employee employee) {


        //1.非空校验
        if (employee == null || StringUtil.isEmpty(employee.getName()) || StringUtil.isEmpty(employee.getPassword()) || StringUtil.isEmpty(employee.getUsername()))  {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常,统一抛出applicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2.按用户名查询用户信息
        System.out.println(employee.getUsername());
        employee existEmployee = employeeMapper.selectEmployeeName(employee.getUsername());
        // 2.1 判断用户是否存在
        if (existEmployee != null) {
            //打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        // 3.新增用户流程,设置默认值
        employee.setPhone(null);
        employee.setId_number(null);
        employee.setSex(null);
        employee.setStatus(1);
        employee.setCreate_user(null);
        employee.setUpdate_user(null);


        //创建日期
        Date date = new Date();
        employee.setCreate_time(date);
        employee.setUpdate_time(date);
        //写入数据库
        int row = employeeMapper.insertSelective(employee);
        if (row != 1){
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //打印日志
        log.info("新增用户成功.username"+employee.getUsername());

    }
}
